package com.talent.jiwen.my;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alipay.sdk.app.AuthTask;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.AliAuthSignResult;
import com.talent.jiwen.http.result.AliPayBindInfo;
import com.talent.jiwen.http.result.AliPayBindStatus;
import com.talent.jiwen.http.result.AuthResult;
import com.talent.jiwen.ui.widgets.LoadWhitDialog;
import com.talent.jiwen.util.ImageUtil;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;



/**
 * Created by qyqx on 2018/8/14.
 * 提现
 */

public class WithdrawActivity extends BaseActivity {

    @BindView(R.id.txt_money)
    TextView txt_money;
    @BindView(R.id.txt_no)
    TextView txt_no;
    @BindView(R.id.txt_tired)
    TextView txt_tired;
    @BindView(R.id.edit_money)
    EditText edit_money;

    @BindView(R.id.txt_all)
    TextView txt_all;

    @BindView(R.id.submit)
    Button submit;

    @BindView(R.id.rl_no_bind)
    RelativeLayout rl_no_bind;

    @BindView(R.id.rl_bind)
    RelativeLayout rl_bind;
    @BindView(R.id.img_alipay)
    ImageView img_alipay;//支付宝头像

    @BindView(R.id.txt_aliName)
    TextView txt_aliName;//支付宝昵称

    @BindView(R.id.txt_change)
    TextView txt_change;

    @BindView(R.id.txt_img_title)
    TextView txt_img_title;



    private static final int SDK_AUTH_FLAG = 2;


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_withdraw;
    }

    @Override
    public String titleName() {
        return "提现";
    }

    @Override
    protected void initData() {
        LoadWhitDialog.show(WithdrawActivity.this);
        mHeadRightText.setVisibility(View.VISIBLE);
        mHeadRightText.setText("规则");
        mHeadRightText.setTextColor(getResources().getColor(R.color.text_gray_9));
        getAliPayBindStatus(false);
    }


    @OnClick({R.id.submit,R.id.txt_tired,R.id.txt_all,R.id.txt_change,R.id.text_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.submit:

                if(aliPayBindState==0){
                    showToast("请先绑定支付宝账号");
                }else{
                    String count=edit_money.getText().toString().trim();

                    if(!Validators.isEmpty(count)){
                        if(!isNumber(count)){
                            showToast("请输入正确的金额格式");
                        }else{
                            double input=Double.parseDouble(count);
                            double total=Double.parseDouble(moneyTotal);
                            if(input>total){
                                showToast("输入金额大于可取金额，请重新输入");
                            }else{
                                userWithdraw(count);
                            }
                        }
                    }else{
                        showToast("请输入您要提现的金额");
                    }
                }

                break;
            case R.id.txt_tired:
//                new MaterialDialog.Builder(this)
//                        .title("输入")
//                        .content("请输入您的支付宝账号")
//                        .inputType(InputType.TYPE_CLASS_NUMBER )//TYPE_CLASS_TEXT| InputType.TYPE_TEXT_VARIATION_PASSWORD
//                        .input(R.string.input_hint, R.string.input_prefill, new MaterialDialog.InputCallback() {
//                            @Override
//                            public void onInput(MaterialDialog dialog, CharSequence input) {
//                                // Do something
//                                txt_no.setText(""+input);
//                            }
//                        }).show();
                getAliAuthSignStr();
                break;
            case R.id.txt_all:
                if(moneyTotal!=null){
                    edit_money.setText(moneyTotal);
                }else{
                    edit_money.setText("0");
                }

                break;

            case R.id.txt_change://更改
                getAliAuthSignStr();
                break;
            case R.id.text_right:
                new MaterialDialog.Builder(this)
                        .title("即问提现规则")
                        .content("1.您账户中可取金额为平台结算您七日前的金额。\n" +
                                "2.目前提现渠道仅限支付宝，其他渠道正在开通中，给您带来的不便敬请谅解。\n" +
                                "3.“即问”在法律允许范围内对本规则拥有解释权。")
                        .positiveText("确定")
                        .showListener(new DialogInterface.OnShowListener() {
                            @Override
                            public void onShow(DialogInterface dialog) {
                            }
                        })
                        .cancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                            }
                        })
                        .dismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                            }
                        }).show();
                break;
        }
    }


    String moneyTotal="0";
    int aliPayBindState=0;

    /**获取用户支付宝绑定状态
     *
     */
    private void getAliPayBindStatus(final boolean showDialog){

        Map<String , String> map = new HashMap<>();
        map.put("studentId" , SPUtil.getUserId());
        Observable observable = ApiFactory.getEducationApiSingleton().getAliPayBindStatus(SPUtil.getToken() , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<AliPayBindStatus>(WithdrawActivity.this) {
            @Override
            protected void _onNext(AliPayBindStatus result) {
                if(result!=null){
                    moneyTotal=result.getValidAmount();
                    txt_money.setText(result.getValidAmount());
                    aliPayBindState=result.getBindingStatus();
                    if(result.getBindingStatus()==0){////是否绑定（0：未绑定 1：已绑定）
                        rl_no_bind.setVisibility(View.VISIBLE);
                        rl_bind.setVisibility(View.GONE);
                    }else{
                        rl_no_bind.setVisibility(View.GONE);
                        rl_bind.setVisibility(View.VISIBLE);
                        if(!Validators.isEmpty(result.getAlipayImage())){
                            txt_img_title.setVisibility(View.VISIBLE);
                            img_alipay.setVisibility(View.VISIBLE);
                            ImageUtil.loadCircleImage(mContext,result.getAlipayImage(),img_alipay);
                        }else{
                            txt_img_title.setVisibility(View.GONE);
                            img_alipay.setVisibility(View.GONE);
                        }

                        if(!Validators.isEmpty(result.getAlipayName())){
                            txt_aliName.setVisibility(View.VISIBLE);
                            txt_aliName.setText("昵称:"+result.getAlipayName());
                        }else{
                            txt_aliName.setVisibility(View.GONE);
                        }
                    }
                }
                if (!showDialog){
                    LoadWhitDialog.dismiss(WithdrawActivity.this);
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
                if (!showDialog){
                    LoadWhitDialog.dismiss(WithdrawActivity.this);
                }
            }
        } , ActivityLifeCycleEvent.DESTROY , lifecycleSubject , showDialog);
    }


    /**用户提现
     *
     */
    private void userWithdraw(String involveMoney){

        Map<String , String> map = new HashMap<>();
        map.put("studentId" , SPUtil.getUserId());
        map.put("involveMoney" , involveMoney);//提现金额
        map.put("withdrawType" , "1");//	提现方式（1：支付宝 2：微信。 注：现只支持支付宝提现）
        Observable observable = ApiFactory.getEducationApiSingleton().userWithdraw(SPUtil.getToken() , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<Void>(WithdrawActivity.this) {
            @Override
            protected void _onNext(Void v) {
                showToast("提现成功");
                EventBus.getDefault().post("refresh");
                getAliPayBindStatus(true);
                edit_money.setText("");
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        } , ActivityLifeCycleEvent.DESTROY , lifecycleSubject , true);
    }


    /**用户绑定支付宝
     *
     */
    private void updateAliPayBindInfo(String aliPayAccessCode){

        Map<String , String> map = new HashMap<>();
        map.put("studentId" , SPUtil.getUserId());
        map.put("aliPayAccessCode" , aliPayAccessCode);
        Observable observable = ApiFactory.getEducationApiSingleton().updateAliPayBindInfo(SPUtil.getToken() , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<AliPayBindInfo>(WithdrawActivity.this) {
            @Override
            protected void _onNext(AliPayBindInfo aliPayBindStatus) {
                if(aliPayBindStatus!=null){
                    aliPayBindState=1;
                    rl_no_bind.setVisibility(View.GONE);
                    rl_bind.setVisibility(View.VISIBLE);
                    if(!Validators.isEmpty(aliPayBindStatus.getAlipayImage())){
                        txt_img_title.setVisibility(View.VISIBLE);
                        img_alipay.setVisibility(View.VISIBLE);
                        ImageUtil.loadCircleImage(mContext,aliPayBindStatus.getAlipayImage(),img_alipay);
                    }else{
                        txt_img_title.setVisibility(View.GONE);
                        img_alipay.setVisibility(View.GONE);
                    }

                    if(!Validators.isEmpty(aliPayBindStatus.getAlipayName())){
                        txt_aliName.setVisibility(View.VISIBLE);
                        txt_aliName.setText("昵称:"+aliPayBindStatus.getAlipayName());
                    }else{
                        txt_aliName.setVisibility(View.GONE);
                    }
                    showToast("绑定成功");
                }else{
                    showToast("绑定失败");
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        } , ActivityLifeCycleEvent.DESTROY , lifecycleSubject , true);
    }




    /**
     * 判断字符串是否是数字
     */
    public static boolean isNumber(String value) {
        return isInteger(value) || isDouble(value);
    }
    /**
     * 判断字符串是否是整数
     */
    public static boolean isInteger(String value) {
        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 判断字符串是否是浮点数
     */
    public static boolean isDouble(String value) {
        try {
            Double.parseDouble(value);
            if (value.contains("."))
                return true;
            return false;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**获取签名字符串并授权
     *
     */
    private void getAliAuthSignStr(){
        final String orginalStr = "apiname=com.alipay.account.auth" + "&"
                        + "app_id=2018090361248261" + "&"
                        +"app_name=mc" + "&"
                        +"auth_type=AUTHACCOUNT" + "&"
                        + "biz_type=openservice" + "&"
                        + "method=alipay.open.auth.sdk.code.get" + "&"
                        + "pid=2088231160244456" + "&"
                        + "product_id=APP_FAST_LOGIN" + "&"
                        + "scope=kuaijie" + "&"
                        + "sign_type=RSA2" + "&"
                        + "target_id=" + SPUtil.getBSUId();

        Map<String , String> map = new HashMap<>();
        map.put("content" , orginalStr);
        Observable observable = ApiFactory.getEducationApiSingleton().getAliPaySign(SPUtil.getToken() , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<AliAuthSignResult>(WithdrawActivity.this) {
            @Override
            protected void _onNext(AliAuthSignResult result) {
                String signStr = result.getSignContent();
                toAliAuth(signStr);
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        } , ActivityLifeCycleEvent.DESTROY , lifecycleSubject , true);
    }

    /**授权
     *
     * @param infoStr
     */
    private void toAliAuth(final String infoStr){
        Runnable authRunnable = new Runnable() {
            @Override
            public void run() {
                AuthTask authTask = new AuthTask(WithdrawActivity.this);
                Map<String , String> result = authTask.authV2(infoStr , true);
                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);

            }
        };
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
//                        Toast.makeText(WithdrawActivity.this,
//                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
//                                .show();
//                        LogUtil.e("user_id======" + authResult.getUserId());
                        if(!Validators.isEmpty(authResult.getAuthCode())){
                            updateAliPayBindInfo(authResult.getAuthCode());
                        }else {

                            showToast("授权失败");
                        }


                    } else {
                        // 其他状态值则为授权失败
//                        Toast.makeText(WithdrawActivity.this,
//                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
                        showToast("授权失败");
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };
}
